package vru;

import robocode.HitByBulletEvent;
import robocode.HitRobotEvent;
import robocode.HitWallEvent;
import robocode.Robot;
import robocode.ScannedRobotEvent;

/**
 * Robot that runs away without never turning its back on robot.
 *
 * @author Russell Vea for ICS 314 Fall 2011.
 */
public class Lessthan20charsyeah extends Robot {
  /** To store bearing and heading of enemy. */
  private double[] coord = new double[2];
  /** To store distance of enemy. */
  private double distance = 10.0;
  /** Set to true when hit by bullet.*/
  private boolean zig = false;

  /**
   * Scan for robot turn towards robot and keep distance to 400.
   */
  public void run() {
    setAdjustRadarForGunTurn(true);
    setAdjustGunForRobotTurn(true);
    while (true) {
      turnRadarRight(360);
      if (this.distance < 200) {
       ahead(this.distance * 6);
      } 
      else if (this.distance < 500) {  
       ahead(this.distance * 2);
      }
    }
  }

  /**
   * @param e the HitByRobot event.
   */
  public void onHitRobot(HitRobotEvent e) {
    zig = zig ? true : false;
    turnRight(90);
    ahead(400);
    scan();
  }
  
  /** 
   * Store bearing,heading and distance.
   *
   * @param e the scanned robot event.
   */ 
  public void onScannedRobot(ScannedRobotEvent e) { 
    coord[0] = e.getBearing() - (getGunHeading() - getHeading());
    this.distance = e.getDistance();
    if (this.distance < 200) { 
      turnRight(e.getBearing() + 90);
      ahead(getBattleFieldHeight());
    }
    moveGun(); 
    fire(2);
  }
  
  /**
   * @param e the event for being hit by bullets.
   */
  public void onHitByBullet(HitByBulletEvent e) {
    double runDirection = e.getBearing();
    if (zig) { 
      zig = false;
    }
    else {
      zig = true;
    }
    out.println(zig);
    runDirection += zig ? 45 : -45;
    turnRight(runDirection);
    ahead(200);
    scan();
  }

  /**
   * Turn away from enemy and reverse 200 pixels.
   *
   *@param e the hit wall event.
   */
  public void onHitWall(HitWallEvent e) {
      turnRight(e.getBearing() + 90);
      scan();
      if (this.distance < 500) {
        ahead(200);
      } 
      else { 
        ahead(getBattleFieldHeight() / 2);        
      }
  }
  
  /**
   * Moves gun to face the enemy.
   */
  public void moveGun() {
    if (coord[0] < 0) {
      turnGunLeft(Math.abs(coord[0]));
    } 
    else {
      turnGunRight(coord[0]);
    }
  }
}
